﻿using System;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace BloggerAutoPosterService.Engine.Utils
{
    public static class XmlUtils
    {
        #region Fields (1)

        private static readonly Regex HTMLRegex = new Regex("<.*?>", RegexOptions.Compiled);

        #endregion Fields

        #region Methods (5)

        // Public Methods (5) 

        public static string CleanTags(this string html)
        {
            return HTMLRegex.Replace(html, string.Empty);
        }

        public static string EscapeXml(this string s)
        {
            var xml = s;
            if (!string.IsNullOrEmpty(xml))
            {
                // replace literal values with entities
                xml = xml.Replace("&", "&amp;");
                xml = xml.Replace("<", "&lt;");
                xml = xml.Replace(">", "&gt;");
                xml = xml.Replace("\"", "&quot;");
                xml = xml.Replace("'", "&apos;");
            }
            return xml;
        }

        public static DateTime SafeDateValue(this XElement input)
        {
            return (input == null) ? DateTime.MinValue : DateTime.Parse(input.Value);
        }

        public static string SafeXElementValue(this XElement input, string defaultValue = "")
        {
            return (input == null) ? defaultValue : input.Value.UnescapeXml().HtmlDecode().ApplyUnifiedYeKe();
        }

        public static string UnescapeXml(this string s)
        {
            var unxml = s;
            if (!string.IsNullOrEmpty(unxml))
            {
                // replace entities with literal values
                unxml = unxml.Replace("&apos;", "'");
                unxml = unxml.Replace("&quot;", "\"");
                unxml = unxml.Replace("&gt;", ">");
                unxml = unxml.Replace("&lt;", "<");
                unxml = unxml.Replace("&amp;", "&");
            }
            return unxml;
        }

        #endregion Methods
    }
}
